''' For each member of active directory group report common properties such as
Name, Username, Email, Title,...

Usage:

    D:\> python show_ad_group_members.py ENV-GIS

    #--- ENV-GIS
    "Name", "Username", "Email", "Title", "Department", "Location"
    "Matt Wilkie", "mhwilkie", "Matt.Wilkie@gov.yk.ca", "Geomatics Analyst", "Environment", "10 Burns Rd."
    ...etc.

Redirect to a CSV file:

    D:\> python show_ad_group_members.py ENV-GIS > env-gis_members.csv
    D:\> start env-gis_members.csv

Double quote a group name with spaces:

    D:\> python show_ad_group_members.py "SDE - distribution list"


Tested with Python 2.6 on Windows 7.
Requires active_directory.py from Tim Golden
(http://timgolden.me.uk/python/active_directory.html)

(c) 2012 Environment Yukon * matt.wilkie@gov.yk.ca
Licensed under the MIT license: http://www.opensource.org/licenses/MIT
'''

import active_directory, sys

group_name = ''.join(sys.argv[1:])
if not group_name:
    print '\nUsage: show_ad_group_members [group name]'
    sys.exit()

def get_members(group_name):
    ''' Recursively retrieve members of group '''
    users = active_directory.find_group(group_name)
    all_users = set()
    for group, groups, users in users.walk():
        all_users.update(users)
    return all_users

def show_report(members):
    ''' Print to console various attributes like Name, Title, etc. for each
        member. The 'members' parameter is expected to be a set of _AD_User
        objects, such as generated by 'get_members'.
    '''
    print '\n\n#--- %s' % group_name
    print '"Name","Username","Email","Title","Department","Location"'
    for member in members:
        print '"%s %s","%s","%s","%s","%s","%s"' % (member.givenName,
        member.sn,  # surname
        member.sAMAccountName,
        member.mail,
        member.title,
        member.department,
        member.physicalDeliveryOfficeName)

if __name__ == '__main__':
    members = get_members(group_name)
    show_report(members)